<?php
	/* user validation script for the login.php page */
	
	//start the session
	session_start();

	//defines the file location
	$file = '../user_data/username_database.txt';

	//reads the file into an array of users & set valid user to false
	$users = file($file);
	$valid_user = false;

	if(isset($_POST['submit']) && $_POST['username'] != '' && $_POST['pword'] != '')
	{
		//assign the entered value to var
		$username = htmlentities($_POST['username'], ENT_QUOTES);
		$pword = htmlentities($_POST['pword'], ENT_QUOTES);

		//loop's through the users array and create the appropriate associated array
		for($i = 0; $i < count($users); $i++)
		{
			//extract each element useing an ' | ' for delimeter and trims any white space around elements 
			$temp = explode(' | ', trim($users[$i]));
	
			//create new array
			$users[$i] = array('username' => $temp[0], 'pword' => rtrim($temp[1]));
	
			if($users[$i]['username'] == $username && $users[$i]['pword'] == $pword)
			{
				//if there is a match set valid user to true and break out of the loop
				$valid_user = true;
				$_SESSION['username'] = $username;
				break;
			}
		}
 
		//if there is no valid user it displays an error message
		//if there is a valid user it logs them into the user home page
		if(!$valid_user)
		{
			$_SESSION['message'] = "<span style='color: red; font-weight: bold;'>You are not a registered user</span>";
			header('Location: ../index.php');
		}
		else
		{
			header('Location: ../user_home.php');
		}
	}
	else
	{
		$_SESSION['message'] = "<span style='color: red; font-weight: bold;'>Not all field have been filled.</span>";
		header('Location: ../index.php');
	}
?>